package com.sl.plugin.step.selenium.interceptor;

import cn.hutool.core.io.FileUtil;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.step.ProcessCompService;
import com.sl.core.engine.step.impl.AbstractProcessComp;
import com.sl.core.utils.JsonUtil;
import lombok.SneakyThrows;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.Command;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v136.network.Network;
import org.openqa.selenium.devtools.v136.network.model.RequestId;
import org.openqa.selenium.devtools.v136.network.model.Response;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

/**
 *
 */
public class SeleniumInterceptorComp extends AbstractProcessComp<WebDriver, WebDriver> implements ProcessCompService {


    public SeleniumInterceptorComp(AbstractProcessCompDescriptor abstractProcessCompDescriptor) {
        super(abstractProcessCompDescriptor);
    }


    @SneakyThrows
    @Override
    public WebDriver input(WebDriver driver) {
        DevTools devTools = ((ChromeDriver) driver).getDevTools();
        devTools.createSession();
        logBasic("DevTools会话已创建");
        String url = meta.getStrAttr("url");

        // 启用Network域监听
        devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
        logBasic("网络请求监听已启用");
        // 创建文件用于保存m3u8链接
        File tempFile = FileUtil.createTempFile();
        logBasic("输出文件已创建: " + tempFile.getAbsolutePath());
        devTools.addListener(Network.responseReceived(), response -> {


            Response res = response.getResponse();
            //
            String url1 = res.getUrl();
            if (url1.contains(url)) {
                // 异步获取响应内容
                CompletableFuture<Void> contentFuture = getResponseContent(devTools, res, response.getRequestId(), tempFile);
                contentFuture.thenRun(() -> System.out.println("响应内容处理完成"));
            }
        });
        return driver;
    }

    @SneakyThrows
    private CompletableFuture<Void> getResponseContent(DevTools devTools, Response res, RequestId requestId, File tempFile) {
        Thread.sleep(8000);
        logBasic("===== 等待成功 =====");
        return CompletableFuture.runAsync(() -> {
            try {
                Command<Network.GetResponseBodyResponse> responseBody1 = Network.getResponseBody(requestId);
                // 获取响应内容
                Network.GetResponseBodyResponse responseBody = devTools.send(
                        responseBody1
                );
                logBasic("===== 获取响应成功 =====");

                // 处理响应内容（可能是JSON、HTML等）

                String rawContent = responseBody.getBody();
                logBasic("响应内容: " + rawContent);
                // 保存链接到文件
                FileUtil.writeString(JsonUtil.toStr(rawContent), tempFile, StandardCharsets.UTF_8);
                logBasic("链接已保存到文件");

                // 可以在这里添加JSON解析逻辑
                // if (isJsonResponse(responseBody.getMimeType())) {
                //     parseJsonContent(content);
                // }

            } catch (Exception e) {
                System.err.println("获取响应内容失败: " + e.getMessage());
            }
        });
    }

}
